package com.zisuyi.game.sdk.module

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.weilele.mvvm.app
import com.weilele.mvvm.gson
import com.weilele.mvvm.utils.activity.navigateTo
import com.weilele.mvvm.utils.activity.onClick
import com.weilele.mvvm.utils.activity.toast
import com.weilele.mvvm.utils.net.getStringBody
import com.zisuyi.game.sdk.base.BaseActivity
import com.zisuyi.game.sdk.base.net.sendHttpByJsonBody
import com.zisuyi.game.sdk.game.GameReceiveMessage
import com.zisuyi.game.sdk.game.bean.AndroidJsBean
import com.zisuyi.game.sdk.game.bean.GameNetworkApiBean
import com.zisuyi.game.sdk.library.R
import com.zisuyi.game.sdk.library.databinding.ActivityHttpBinding
import com.zisuyi.game.sdk.library.login.IGameLogin
import okhttp3.Call
import okhttp3.Callback
import java.io.IOException

class HttpActivity : BaseActivity<ActivityHttpBinding>() {
    companion object {
        val userInfo =
            "{\"code\":0,\"json\":\"{\\\"api\\\":\\\"/api/v2/user/\\\",\\\"method\\\":\\\"post\\\",\\\"params\\\":\\\"{\\\\\\\"id\\\\\\\":\\\\\\\"112549185697687926102\\\\\\\",\\\\\\\"name\\\\\\\":\\\\\\\"zhiyi xie\\\\\\\",\\\\\\\"thumb\\\\\\\":\\\\\\\"https://lh6.googleusercontent.com/-hz4FBPJ2jio/AAAAAAAAAAI/AAAAAAAAAAA/AMZuucmVbHRH7MSI0JjcEvFOK9U0wp667Q/s96-c/photo.jpg\\\\\\\",\\\\\\\"token\\\\\\\":\\\\\\\"eyJhbGciOiJSUzI1NiIsImtpZCI6ImUxOTdiZjJlODdiZDE5MDU1NzVmOWI2ZTVlYjQyNmVkYTVkNTc0ZTMiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJhenAiOiIyMTEyNjEwOTE3MzEtc3VoNzdtaDgyaG1xYm0zaDlqbGFyajVuNXRncDNtZzAuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiIyMTEyNjEwOTE3MzEtb2VlNHFjZnI0YzRkbmJ1MGNxN2twMmhhOGw2OXE2M3UuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJzdWIiOiIxMTI1NDkxODU2OTc2ODc5MjYxMDIiLCJlbWFpbCI6InhpbmNoYW9uZW5nMjAyMEBnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwibmFtZSI6InpoaXlpIHhpZSIsInBpY3R1cmUiOiJodHRwczovL2xoNi5nb29nbGV1c2VyY29udGVudC5jb20vLWh6NEZCUEoyamlvL0FBQUFBQUFBQUFJL0FBQUFBQUFBQUFBL0FNWnV1Y21WYkhSSDdNU0kwSmpjRXZGT0s5VTB3cDY2N1Evczk2LWMvcGhvdG8uanBnIiwiZ2l2ZW5fbmFtZSI6InpoaXlpIiwiZmFtaWx5X25hbWUiOiJ4aWUiLCJsb2NhbGUiOiJlbiIsImlhdCI6MTYwNzkxMzI2NywiZXhwIjoxNjA3OTE2ODY3fQ.b4KCX3Y4QDtVoSLH5tfs6O93_wzQW4N-yTl7e6INoqOBwmqUeKWUPRWAVMz0yeU2QnjsGS29iOM-29qkhHg0PGInEdqVhdMvGmZYqhYe1-QE9XlavHeoHZleuagc4gDNi-NSbmp33SloTbbVtlTZjo0_lbpn9UIrFcf5suD-46ipM3O--lBZCC9-vvq1EbPMPSgB_oyfzmMvvMd1qG9TcqJnGupHBQGyJ4Y7xiWCWtOxCI9q5m8IlIzWxzFbCOY2zen4qk9jUy7ZC1wiStsGpwX1gvVZsJCt5M6hThkHHFYCih9BIhmARHXrQ9UyWYwtbgJYbmkD22KR6hnNityJdQ\\\\\\\",\\\\\\\"type\\\\\\\":\\\\\\\"google\\\\\\\"}\\\"}\",\"type\":\"TYPE_HTTP_API\"}"

        fun start(appCompatActivity: AppCompatActivity) {
            appCompatActivity.navigateTo<HttpActivity>()
        }

        fun getTestUser(): IGameLogin.UserInfo {
            return gson.fromJson(
                gson.fromJson(
                    gson.fromJson(
                        HttpActivity.userInfo,
                        AndroidJsBean::class.java
                    ).json, GameNetworkApiBean::class.java
                ).params, IGameLogin.UserInfo::class.java
            )
        }

        fun netRequest(message: AndroidJsBean, resultCall: Function1<String, Unit>) {
            val bean = gson.fromJson(message.json, GameNetworkApiBean::class.java)
            val api = bean.api
            val params = bean.params
            api.sendHttpByJsonBody(params, method = bean.method).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    message.message = e.toString()
                    message.code = GameReceiveMessage.ERROR_CODE_HTTP_ERROR
                    //消息发送给游戏
                    resultCall.invoke(gson.toJson(message))
                }

                override fun onResponse(call: Call, response: okhttp3.Response) {
                    try {
                        val bodyStr = response.getStringBody()
                        if (bodyStr.isNullOrBlank()) {
                            onFailure(call, IOException(response.message))
                        } else {
                            bean.data = bodyStr
                            message.json = gson.toJson(bean)
                            //消息发送给游戏
                            resultCall.invoke(gson.toJson(message))
                        }
                    } catch (e: Throwable) {
                        e.printStackTrace()
                        onFailure(call, IOException(e.message))
                    }
                }
            })
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_http)
        mBinding.btLogin.onClick {
            mBinding.etApi.setText(userInfo)
            mBinding.btRequest.performClick()
        }
        mBinding.btClear.onClick {
            mBinding.etApi.setText(null)
            mBinding.etResult.setText(null)
        }
        mBinding.btResult.onClick {
            copyToClipboard(mBinding.etResult.text.toString())
        }
        mBinding.btRequest.onClick {
            val api = mBinding.etApi.text.toString()
            if (api.isBlank()) {
                "不能为null".toast()
                return@onClick
            }
            mBinding.btRequest.isEnabled = false
            mBinding.btRequest.text = "请求中..."
            netRequest(gson.fromJson(api, AndroidJsBean::class.java)) {
                mBinding.etResult.post {
                    mBinding.btRequest.isEnabled = true
                    mBinding.btRequest.text = "发送请求"
                    mBinding.etResult.setText(it)
                }
            }
        }
    }

    fun copyToClipboard(text: String) {
        //获取剪贴板管理器：
        val cm = app.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建普通字符型ClipData
        val mClipData = ClipData.newPlainText("Label", text)
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData)
        "Copy Success".toast()
    }
}